package com.cbb.display.controller;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.cbb.display.entity.Goods;
import com.cbb.display.service.GoodsService;
import com.cbb.display.util.CommonUtil;
import com.cbb.display.enums.ErrorEnum;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bigbomb
 * @since 2020-01-29
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
	
@Autowired
private GoodsService goodsService;

   @GetMapping("/list")
	public JSONObject list() {
	List<Goods> goodsList = goodsService.list();
	return CommonUtil.successJson(goodsList);
		
	}



	@PostMapping("/add")
    public JSONObject add(String goodsformlist) {
		List<Goods>  idcollection = new ArrayList<Goods>();
		List<Goods>  noidcollection =new ArrayList<Goods>();
		List<Goods>  collection = JSONObject.parseArray(goodsformlist, Goods.class);
		for(Goods goods : collection)
		{
			if(goods.getId()== null )
			{
				noidcollection.add(goods);
			}
			else {
				idcollection.add(goods);
			}
		}
		boolean status = goodsService.addGoods(noidcollection,idcollection);
	    
	    if(status)
	    {
	    	return CommonUtil.successJson();
	    }
	    else {
			return CommonUtil.errorJson(ErrorEnum.E_500);
		}
   }
	
	@PostMapping("/update")
    public JSONObject update(String goods) {
	Goods goodObject = JSONObject.parseObject(goods,Goods.class);
    boolean status = goodsService.updateById(goodObject);
    if(status)
    {
    	return CommonUtil.successJson();
    }
    else {
		return CommonUtil.errorJson(ErrorEnum.E_500);
	 }
	}
    
    
	@PostMapping("/del")
    public JSONObject del(Long id) {
    boolean status = goodsService.removeById(id);
    if(status)
    {
    	return CommonUtil.successJson();
    }
    else {
		return CommonUtil.errorJson(ErrorEnum.E_500);
	}
    	
    }
	
}
